import pickle
import os

solved = lambda x: sum(x['results'][prob]['solved'] for prob in x['results'])
score = lambda x: sum(x['results'][prob]['score'] for prob in x['results'])
attempts = lambda x: sum(x['results'][prob]['attempts'] if x['results'][prob]['score'] else 0 for prob in x['results'])

ST_FILE = os.sys.argv[1]
try:
  FILTER = eval('lambda x:' + ' '.join(os.sys.argv[2:]))
except:
  FILTER = lambda x: True

with open('results.pcl', 'rb') as rh:
  RESULTS = pickle.load(rh)
  TIME = pickle.load(rh)

RESULTS = list(filter(FILTER, RESULTS))

RESULTS.sort(key = lambda x: (
   -sum(x['results'][prob]['score'] for prob in x['results']),
   -sum(x['results'][prob]['solved'] for prob in x['results']),
   sum(x['results'][prob]['attempts'] if x['results'][prob]['score'] else 0 for prob in x['results']),
   x['login'].upper(),
))

fields = [
  ('Место', lambda x: x['place']),
  ('Участник', lambda x: x['login']),
  ('Имя', lambda x: '%s %s' % (x['name'], x['surname'])),
  ('Класс', lambda x: x['grade']),
  ('Город', lambda x: x['city']),
]

PREF_H = len(fields)

for prob in sorted(RESULTS[0]['results']):
  fields.append(
    ('<center><b>%s</b></center>' % prob, 
      (lambda prob: (
        lambda x: '' if (not x['results'][prob]['attempts']) else ((('<center><b>%d</b><br/><small>%d</small></center>' if x['results'][prob]['solved'] else '<center>%d<br/><small>%d</small></center>') % (x['results'][prob]['score'], x['results'][str(prob)]['attempts']))))
      )(prob)
    )
  )

PROB_N = len(fields) - PREF_H

fields += [
  ('<center>Баллы</center>', lambda x: '<center>%d</center>' % sum(x['results'][prob]['score'] for prob in x['results'])),
  ('<center>Посылок</center>', lambda x: '<center>%d</center>' % sum(x['results'][prob]['attempts'] if x['results'][prob]['score'] else 0 for prob in x['results'])),
  ('<center>Решено</center>', lambda x: '<center>%d</center>' % sum(x['results'][prob]['solved'] for prob in x['results'])),
]

PLACES = [1]
for x in range(1, len(RESULTS)):
  if (sum(RESULTS[x]['results'][prob]['score'] for prob in RESULTS[x]['results']) == sum(RESULTS[x-1]['results'][prob]['score'] for prob in RESULTS[x-1]['results'])) and \
     (sum(RESULTS[x]['results'][prob]['solved'] for prob in RESULTS[x]['results']) == sum(RESULTS[x-1]['results'][prob]['solved'] for prob in RESULTS[x-1]['results'])) and \
     (sum(RESULTS[x]['results'][prob]['attempts'] if RESULTS[x]['results'][prob]['score'] else 0 for prob in RESULTS[x]['results']) == sum(RESULTS[x-1]['results'][prob]['attempts'] if RESULTS[x-1]['results'][prob]['score'] else 0 for prob in RESULTS[x-1]['results'])):
    PLACES += [PLACES[-1]]
  else:
    PLACES += [x+1]

PLACES += [float("+inf")]
cn = 0
while cn < len(PLACES)-1:
  cp = cn+1
  while PLACES[cp] == PLACES[cn]:
    cp += 1
  if cp != cn+1:
    for i in range(cn, cp):
      PLACES[i] = '%d-%d' % (cn+1, cp)
  else:
    PLACES[cn] = '%d' % cp
  cn = cp

for i in range(len(RESULTS)):
  RESULTS[i]['place'] = PLACES[i]
  

with open(ST_FILE, 'w') as resh:
  resh.write(open('generic_html_head.html').read())

  resh.write('<div class="timing">Обновлено %s</div>' % TIME)

  resh.write('<table class="nice_table" width="100%">')
  resh.write('<thead><tr>')
  resh.write('<td colspan="%d" align=right>Решений</td>' % PREF_H)
  for prob in sorted(RESULTS[0]['results']):
    resh.write('<td><center>%d</center></td>' % len(list(filter(lambda x: x['results'][prob]['solved'], RESULTS))))
  resh.write('<td colspan="%d"></td>' % (len(fields) - PREF_H - PROB_N))

  resh.write('</thead><thead><tr>')
  resh.write('<td colspan="%d" align=right>Посылок</td>' % PREF_H)
  for prob in sorted(RESULTS[0]['results']):
    resh.write('<td><center>%d</center></td>' % sum(x['results'][prob]['attempts'] for x in RESULTS))
  resh.write('<td colspan="%d"></td>' % (len(fields) - PREF_H - PROB_N))

  resh.write('</thead><thead><tr>')
  resh.write('<td colspan="%d" align=right>Средний балл</td>' % PREF_H)
  for prob in sorted(RESULTS[0]['results']):
    resh.write(r'<td><center>%d</center></td>' % (sum(x['results'][prob]['score'] for x in RESULTS) / len(RESULTS)))
  resh.write('<td colspan="%d"></td>' % (len(fields) - PREF_H - PROB_N))

  resh.write('</thead><thead><tr>')
  resh.write('<td colspan="%d" align=right>Средний балл среди делавших посылки</td>' % PREF_H)
  for prob in sorted(RESULTS[0]['results']):
    resh.write(r'<td><center>%d</center></td>' % (sum(x['results'][prob]['score'] for x in RESULTS) / len(list(filter(lambda x: x['results'][prob]['attempts'] ,RESULTS)))))
  resh.write('<td colspan="%d"></td>' % (len(fields) - PREF_H - PROB_N))

  resh.write('<thead><tr>')
  for td, ltd in fields:
    resh.write('<td>%s</td>' % td)

  resh.write('</tr></thead><tbody>')
  for res in RESULTS:
    resh.write('<tr>')
    for td, ltd in fields:
      resh.write('<td>%s</td>' % ltd(res))
    resh.write('</tr>')
  resh.write('</tbody></table>')
  resh.write(open('generic_html_bottom.html').read())
